package org.iteam.xlz.core.service.base;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.iteam.commons.utils.DateUtil;
import org.iteam.core.utils.SqlBuilder;
import org.iteam.db.BaseService;
import org.iteam.xlz.core.entity.base.Versions;

public class VersionService extends BaseService<Versions>{
	static VersionService instance;
	
	private VersionService(){}
	
	public static VersionService getInstance(){
		if(null==instance){
			instance=new VersionService();
		}
		return instance;
	}
	
	public Versions findOne(String vid){
		try {
			return super.show("select * from versions where vid=?",vid);
		} catch (SQLException e) {
			e.printStackTrace();
			return new Versions();
		}
	}
	
	public boolean delete(String vid){
		try {
			return super.updates("delete from versions where vid=?",vid)==1;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public long counts(){
		try {
			return super.counts("select count(1) from versions where 1=1");
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
	}
	
	public List<Versions> query(long page,long rows){
		try {
			return super.query("select * from versions where 1=1 order by createtime desc limit ?,?",(page-1)*rows,rows);
		} catch (SQLException e) {
			e.printStackTrace();
			return new ArrayList<Versions>();
		}
	}
	
	public boolean create(Versions model){
		model.setVid(UUID.randomUUID().toString().replace("-","").toUpperCase());
		SqlBuilder sql=SqlBuilder.createInsert("versions");
		sql.addField("vid",model.getVid());
		sql.addField("versionnumber",model.getVersionnumber());
		sql.addField("platform",model.getPlatform());
		sql.addField("ismustupgrade",model.getIsmustupgrade());
		sql.addField("lowestversion",model.getLowestversion());
		sql.addField("url",model.getUrl());
		if(StringUtils.isNotBlank(model.getIntro())){
			sql.addField("intro",model.getIntro());
		}
		sql.addField("creator",model.getCreator());
		sql.addField("createtime",DateUtil.currentTime());
		try {
			return super.updates(sql.getSql(),sql.getParams())>0;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean update(Versions model){
		SqlBuilder sql=SqlBuilder.createUpdate("versions");
		sql.addField("versionnumber",model.getVersionnumber());
		sql.addField("platform",model.getPlatform());
		sql.addField("ismustupgrade",model.getIsmustupgrade());
		sql.addField("lowestversion",model.getLowestversion());
		sql.addField("url",model.getUrl());
		sql.addField("intro",model.getIntro());
		sql.addWhere("vid",model.getVid());
		try {
			return super.updates(sql.getSql(),sql.getParams())==1;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}		
	}
}
